import type React from "react";
import { useEffect, useState } from "react";
import type { JSX } from "react/jsx-runtime"
import mitt from 'mitt'
type EventType = {
  'brother-emit2': MessageType;
}
const mittInstance = mitt<EventType>()
/**
 * 父向子组件传递 props
 * 
    支持的类型如下：
    string title={'测试'}
    number id={1}
    boolean isGirl={false}
    null empty={null}
    undefined empty={undefined}
    object obj={ { a: 1, b: 2 } }
    array arr={[1, 2, 3]}
    function cb={(a: number, b: number) => a + b}
    JSX.Element element={<div>测试</div>}
 */
interface Props {
  title?: string;
  id: number;
  isGirl: boolean;
  empty: null;
  unEmpt: undefined;
  obj: { a: number; b: number };
  arr: number[];
  cb: (a: number, b: number) => number;
  element: JSX.Element;
  children?: React.ReactNode
}

interface MessageType {
  message: string
}



const event = new Event('brother-emit')
// 默认值：
// 第一种方式：{title = '默认title'}
const Child1 = ({title = '默认title', ...props}: Props) => {
  console.log(title, props);
  
  const handleEmit = () => {
    event.params = { message: '兄弟你好' }
    window.dispatchEvent(event)
  }
  const handleEmit2 = () => {
    mittInstance.emit('brother-emit2', { message: '兄弟你好2' })
  }
  return <>
    <h1 onClick={() => props.cb(1, 2)}>子组件1</h1>
    {props.children}
    <button onClick={handleEmit}>定义事件模型方式给兄弟发信息</button>
    <button onClick={handleEmit2}>mitt给兄弟发信息</button>
  </>
};
// 第二种方式
// const defaultProps = {
//   title: '默认title'
// }
// const Child1: React.FC<Props> = (props) => {
//   const {title} = {...defaultProps, ...props}
//   console.log(title, props);
//   return <div>子组件1</div>;
// };

const Child2 = () => {
  useEffect(() => {
    const fn = (e: Event) => {  
      console.log(e.params.message)
    }
    window.addEventListener('brother-emit', fn)
    mittInstance.on('brother-emit2', (e) => {
      console.log(e.message)
    })
    return () => {
      window.removeEventListener('brother-emit', fn)
      mittInstance.off('brother-emit2', (e) => {
      console.log(e.message)
    })
    }
  }, [])
  return <h1>子组件2</h1>;
}


export default function Comp2() {
  const [count, setCount] = useState(0)
  return (
    <>
      <div>组件通信实例</div>
      <div>
        知识点: 
        1、父向子组件传递props；2、定义默认值；3、children属性（类似vue的slot）；4、兄弟组件通信（自定义事件或mitt）
      </div>
      <button onClick={() => setCount(count + 1)}>count++</button>
      <Child1
        title="测试"
        id={count}
        isGirl={false}
        empty={null}
        unEmpt={undefined}
        obj={{ a: 1, b: 2 }}
        arr={[1, 2, 3]}
        cb={(a: number, b: number) => {
          console.log(a, b);
          return a + b
        }}
        element={<div>测试</div>}
      >
        <h1 style={{ color: "red" }}>Children内容</h1>
        <p>Children内容2</p>
      </Child1>
      <Child2 />
    </>
  );
}

declare global {
  interface Event {
    params: MessageType
  }
}
